interface INewsItem {
  id: string;
  title: string;
  description: string;
  imageUrl: string;
  createTime: string;
  category: string;
  tags: string[];
}

interface IPageData {
  categoryId: string;
  categoryName: string;
  newsList: INewsItem[];
}

import { API } from '../../config/api';
import request from '../../utils/request';

Page<IPageData, any>({
  data: {
    categoryId: '',
    categoryName: '',
    newsList: [],
  },

  onLoad(options: { categoryId: string; categoryName: string }) {
    const { categoryId, categoryName } = options;
    this.setData({
      categoryId,
      categoryName,
    });
    console.log('categoryId', categoryId);
    console.log('categoryName', categoryName);
    this.getNewsList();
  },

  goToDetail(e: any) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`,
    });
  },

  async getNewsList() {
    try {
      const params = {
        pageNum: 1,
        pageSize: 10,
        categoryId: this.data.categoryId,
      };

      const res = await request({
        data: params,
        url: API.news.list,
        method: 'POST',
        loading: true,
      });
      console.log('新闻数据', res);
      const newsData = (
        res as {
          data: {
            list: Array<{
              id: string;
              title: string;
              summary: string;
              createTime: string;
              categoryName: string;
              tagNames: string[];
            }>;
          };
        }
      ).data.list.map((item, index: number) => ({
        id: item.id,
        title: item.title,
        description: item.summary,
        imageUrl: `https://picsum.photos/200/150?random=${index + 20}`,
        createTime: item.createTime,
        category: item.categoryName,
        tags: item.tagNames,
      }));

      this.setData({
        newsList: newsData,
      });
    } catch (error) {
      console.error('获取新闻列表失败：', error);
    }
  },
});
